/** 
* @Title: CachedDB.java 
* @Package com.lh.threadtest.t10 
* @Description: TODO
* @author Liu 
* @date 2018年1月17日 下午6:12:33 
* @version V1.0 
*/
package com.lh.threadtest.t10;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/** 
* @ClassName: CachedDB 
* @Description: TODO
* @author Liu
* @date 2018年1月17日 下午6:12:33 
*  
*/
public class CachedDB {
	
	
	/***
	* @Title: main 
	* @Description: TODO
	* @param @param args
	* @return void
	* @throws 
	*/
	public static void main(String[] args) {
		Business business = new Business();
		
		for(int i = 1; i <= 3; i++){
			for(int j = 1; j <= 3; j++){
				final int target = j;
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						System.out.println(Thread.currentThread().getName() + " val: " + business.getAndSet(target + ""));
					}
				},"threadName-" + target).start();
			}
		}
	}
}

class Business{
	private static Map<String, Integer> cachedMap = new HashMap<>();
	
	private ReadWriteLock rwl = new ReentrantReadWriteLock();
	
	static{
		cachedMap.put("xiaofang", 1);
		cachedMap.put("xiaobai", 2);
		cachedMap.put("xiaomei", 3);
	}
	
	public Integer getAndSet(String name){
		rwl.readLock().lock();
		Integer target = null;
		try {
			target = cachedMap.get(name);
			if(Objects.isNull(target)){
				rwl.readLock().unlock();
				rwl.writeLock().lock();
				try {
					if(Objects.isNull(target)){
						target = name.equals("1") ? 10 : (name.equals("2") ? 100 : 1000);//去查询数据库
						cachedMap.put(name, target);
					}
				} finally {
					rwl.writeLock().unlock();
				}
				rwl.readLock().lock();
				
				//use...
				
			}
		} finally {
			rwl.readLock().unlock();
		}
		return target;
	}	
}
